<template>
  <div class="p-4">
    <el-card class="box-card">
      <div slot="header" class="clearfix flex justify-between">
        <el-form class="flex-grow" inline>
          <el-form-item>
            <el-button
              icon="el-icon-plus"
              type="success"
              @click="deBounceWrap(handleAdd)"
            >新增
            </el-button
            >
            <el-button
              icon="el-icon-delete"
              type="danger"
              @click="deBounceWrap(handleDelAll)"
            >批量删除
            </el-button
            >
          </el-form-item>
        </el-form>

        <div class="flex-grow-0">
          <el-select
            v-model="listQuery.sale_status"
            clearable
            placeholder="请选择销售状态"
          >
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
          <el-input
            v-model="listQuery.gift_name"
            class="ml-4"
            clearable
            placeholder="请输入礼物名称"
            style="width: 35%"
          ></el-input>
          <el-button
            class="el-icon-search p-1 text-white text-2xl bg-green-500 cursor-pointer"
            type="primary"
            @click="getList"
          >搜索
          </el-button
          >
        </div>
      </div>

      <el-table :data="data" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="id" width="100px"></el-table-column>
        <el-table-column label="礼物名称" prop="name"></el-table-column>
        <el-table-column label="互动类型" prop="op_type_name"></el-table-column>
        <el-table-column label="礼物说明" prop="desc"></el-table-column>
        <el-table-column label="亲密值" prop="cardiac"></el-table-column>
        <el-table-column label="状态" prop="sale_status_name">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.sale_status_name === '下架' ? 'danger' : 'success'
              "
            >{{ scope.row.sale_status_name }}
            </el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit"></el-table-column>
        <el-table-column label="价格（回声币）" prop="price"></el-table-column>
        <el-table-column label="图片" prop="picture">
          <template slot-scope="{ row }">
            <el-popover max-width="420" placement="right" trigger="hover">
              <img
                :src="row.picture"
                alt=""
                style="max-width: 200px; max-height: 200px"
              />
              <img
                slot="reference"
                :src="row.picture"
                alt=""
                style="width: 50px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="动效" prop="special">
          <template slot-scope="scope">
            <div v-if="/.mp4$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <video
                  :src="scope.row.special"
                  controls
                  style="max-width: 200px"
                ></video>
                <video
                  slot="reference"
                  :src="scope.row.special"
                  autoplay
                  loop
                  muted
                  style="width: 50px"
                ></video>
              </el-popover>
            </div>
            <div v-else-if="/.webp$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <img
                  :src="scope.row.special"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.special"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </div>
            <div v-else-if="/.svga$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <!-- <svga :src="scope.row.special" :options="options"> -->
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="可用房间类型" prop="usable_room_sys_type">
        </el-table-column>
        <el-table-column label="操作" width="270px">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain
              size="mini"
              type="primary"
              @click="deBounceWrap(handleEdit, scope.row)"
            >编辑
            </el-button
            >
            <el-button
              icon="el-icon-delete"
              plain
              size="mini"
              type="danger"
              @click="deBounceWrap(handleDel, scope.row)"
            >删除
            </el-button
            >
            <el-button
              v-if="scope.row.sale_status_name !== '下架'"
              icon="el-icon-receiving"
              plain
              size="mini"
              type="info"
              @click="deBounceWrap(handleStatus, scope.row)"
            >下架
            </el-button
            >
            <el-button
              v-if="scope.row.sale_status_name === '下架'"
              icon="el-icon-receiving"
              plain
              size="mini"
              type="warning"
              @click="deBounceWrap(handleStatus, scope.row)"
            >上架
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <cus-pagination
        :limit.sync="listQuery.page_size"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="titleOptions[title]"
      :visible.sync="dialogVisible"
      width="40%"
      @close="handleClear"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="操作类型" prop="op_type">
          <el-select
            v-model="form.op_type"
            clearable
            placeholder="请选择操作类型"
          >
            <el-option
              v-for="item in operationOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              clearable
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="礼物名称" prop="gift_name">
          <el-input
            v-model="form.gift_name"
            clearable
            placeholder="请输入礼物名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="礼物价格" prop="gift_price">
          <el-input
            v-model="form.gift_price"
            clearable
            placeholder="请输入礼物价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="亲密值" prop="gift_cardiac">
          <el-input
            v-model="form.gift_cardiac"
            clearable
            placeholder="请输入亲密值"
          ></el-input>
        </el-form-item>
        <el-form-item label="礼物说明" prop="gift_desc">
          <el-input
            v-model="form.gift_desc"
            clearable
            placeholder="请输入礼物说明"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input
            v-model="form.unit"
            clearable
            placeholder="请输入单位"
          ></el-input>
        </el-form-item>

        <el-form-item label="图片" prop="picture">
          <el-upload
            :before-upload="handleBeforeUploadPicture"

            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="form.picture" :src="form.picture" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="动效" prop="special">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="handleBeforeUploadSpecial"
            :file-list="specialList"

            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="text"
          >
            <el-button slot="trigger" size="small" type="primary"
            >上传特效
            </el-button
            >
          </el-upload>
        </el-form-item>

        <el-form-item label="销售状态" prop="sale_status">
          <el-radio v-model="form.sale_status" :label="1">上架</el-radio>
          <el-radio v-model="form.sale_status" :label="0">下架</el-radio>
        </el-form-item>

        <el-form-item label="选择可用房间系统类型" prop="usable_room_sys_type">
          <el-select
            v-model="usableroom"
            clearable
            multiple
            placeholder="请选择可用房间系统类型"
            @change="handleSelect"
          >
            <el-option
              v-for="item in userRoomList"
              :key="item.id"
              :label="item.room_type_name"
              :value="item.id"
              clearable
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button plain type="primary" @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
        >提交
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style: normal; color: red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {
  addGiftList,
  delGiftList,
  editGiftList,
  editStatus,
  getListApi,
  giftDetail,
  giftType,
  roomType
} from '@/api/roomGift/interactiveGifts'

export default {
  data() {
    return {

      specialList: [],
      data: [],
      listQuery: {
        gift_name: undefined,
        sale_status: undefined,
        page: 1,
        page_size: 20
      },
      total: 0,
      titleOptions: {
        add: '新增',
        edit: '编辑'
      },
      title: 'add',
      rowData: {},
      operationOptions: [], // 操作类型
      userRoomList: [], //可用房间类型
      usableroom: [], // 可用房间 的多选数组
      options: [],
      selectedOptions: [],
      defaultParams: {
        label: 'title',
        value: 'id',
        children: 'children'
      },

      form: {
        category_id: undefined,
        op_type: undefined,
        gift_name: undefined,
        gift_price: undefined,
        unit: undefined,
        picture: undefined,
        special: undefined,
        sale_status: undefined,
        usable_room_sys_type: undefined,
        gift_desc: undefined,
        gift_cardiac: undefined //亲密值
      },
      rules: {
        category_id: [
          { required: true, message: '请选择分类id', trigger: 'change' }
        ],
        op_type: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        gift_name: [
          { required: true, message: '请输入礼物名称', trigger: 'blur' }
        ],
        gift_desc: [
          { required: true, message: '请输入礼物说明', trigger: 'blur' },
          { max: 100, message: '礼物说明不能超过100个字符' }
        ],
        gift_cardiac: [
          { required: true, message: '请输入亲密值', trigger: 'blur' }
        ],
        gift_price: [
          { required: true, message: '请输入礼物价格', trigger: 'blur' }
        ],
        unit: [{ required: true, message: '请输入礼物单位', trigger: 'blur' }],
        picture: [{ required: true, message: '请上传图片', trigger: 'change' }],
        special: [{ required: true, message: '请上传特效', trigger: 'change' }],
        sale_status: [
          { required: true, message: '请选择销售状态', trigger: 'change' }
        ],
        usable_room_sys_type: [
          {
            required: true,
            message: '请选择可用房间系统状态',
            trigger: 'change'
          }
        ]
      },
      dialogVisible: false,
      //删除
      deleteDialogVisible: false,
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      //当前行id
      currentId: ''
    }
  },
  created() {
    this.getList()
    this.getGiftType()
    this.getRoomType()
  },
  methods: {
    //列表
    getList() {
      let data = JSON.parse(JSON.stringify(this.listQuery))
      if (!this.listQuery.sale_status) {
        data.status = -1
      }
      getListApi(data).then(res => {
        this.data = res.data.data
        this.total = res.data.total
      })
    },
    //获取操作类型下拉框（根据操作类型分类）
    getGiftType() {
      giftType({ op_type_category: 2 }).then(res => {
        this.operationOptions = res.data
      })
    },

    //获取所有房间类型
    getRoomType() {
      roomType({ type: 1 }).then(res => {
        let arr = [{ id: 0, room_type_name: '全部' }]
        this.userRoomList = [...arr, ...res.data]
      })
    },
    handleSelect(value) {
      this.usableroom = value
      if (this.usableroom.length) {
        this.form.usable_room_sys_type = this.usableroom.reduce((pre, currRow) => {
          pre += `,${currRow}`
          return pre
        })
      }
    },
    handleSuccess() {
      this.form.picture = this.ossLastImgUrl
    },
    handleBeforeUploadPicture(file) {
      const isPic =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp'

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic) {
        this.$message.error('请上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleBeforeUploadSpecial(file) {
      const isMp4 = file.type === 'video/mp4'
      if (!isMp4) {
        this.$message.error('上传特效只能为 MP4 格式!')
      }
      return isMp4
    },
    handleSpecialFlagBigRemove(res) {
      this.form.special = undefined
      this.specialList = []
    },
    handleSpecialFlagBigSuccess(res) {
      this.form.special = res.data.url
      this.specialList = [{ name: res.data.url }]
    },
    //新增
    handleAdd() {
      this.title = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.title = 'edit'
      this.rowData = row

      this.form.special = this.rowData.special
      if (row.special) {
        this.specialList = [{ name: row.special }]
      }
      this.form.op_type = this.rowData.op_type
      this.form.gift_name = this.rowData.name
      this.form.gift_price = this.rowData.price
      this.form.gift_desc = this.rowData.desc
      this.form.unit = this.rowData.unit
      if (this.rowData.sold === 1) {
        this.form.sale_status = this.rowData.sold
      } else {
        this.form.sale_status = 0
      }
      this.form.picture = this.rowData.picture
      this.form.gift_cardiac = this.rowData.cardiac
      //获取详情接口 数据回显
      giftDetail({ id: row.id }).then(res => {
        this.form.category_id = res.data.category_id
        if (res.data.category_id) {
          this.selectedOptions = res.data.category_id
        }
        this.usableroom = res.data.room_sys_type.map(item => {
          return parseInt(item)
        })
        this.form.usable_room_sys_type = this.rowData.room_sys_type.toString()
      })

      this.dialogVisible = true
    },
    handleSumbit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === 'add') {
            let data = {
              category_id: this.form.category_id,
              op_type: this.form.op_type,
              gift_name: this.form.gift_name,
              gift_price: this.form.gift_price,
              unit: this.form.unit,
              picture: this.form.picture,
              special: this.form.special,
              usable_room_sys_type: this.form.usable_room_sys_type + '',
              sale_status: this.form.sale_status,
              gift_desc: this.form.gift_desc,
              gift_cardiac: this.form.gift_cardiac
            }
            addGiftList(data).then(res => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.getList()
                this.dialogVisible = false
              } else {
              }
            })
          }
          if (this.title === 'edit') {
            let data1 = {
              id: this.rowData.id,
              category_id: this.form.category_id,
              op_type: this.form.op_type,
              gift_name: this.form.gift_name,
              gift_price: this.form.gift_price,
              unit: this.form.unit,
              picture: this.form.picture,
              special: this.form.special,
              usable_room_sys_type: this.form.usable_room_sys_type + '',
              sale_status: this.form.sale_status,
              gift_desc: this.form.gift_desc,
              gift_cardiac: this.form.gift_cardiac
            }
            editGiftList(data1).then(res => {
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.getList()
                this.dialogVisible = false
              }
            })
          }
        } else {

          return false
        }
      })
    },
    //清空表单
    handleClose() {
      this.dialogVisible = false
    },
    handleClear() {
      this.$refs['form'].resetFields()
      this.form = {
        category_id: undefined,
        op_type: undefined,
        gift_name: undefined,
        gift_price: undefined,
        unit: undefined,
        picture: undefined,
        special: undefined,
        sale_status: undefined,
        usable_room_sys_type: undefined,
        gift_desc: undefined,
        gift_cardiac: undefined //亲密值
      }
      this.specialList = []
      this.selectedOptions = []
      this.usableroom = []
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //批量删除
    handleDelAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */
        const ids = this.multipleSelection.reduce(
          (pre, currRow) => {
            pre += `${currRow.id},`
            return pre
          },
          ''
        )
        delGiftList({ ids })
          .then(() => this.$message.success('删除成功！'))
          .catch(console.error)
          .finally(() => /* 刷新数据 */ {
            this.multipleSelection = []
            this.getList()
          })
      } /* 不存在勾选数据 */ else {
        this.$message.warning('请勾选要删除的数据！')
      }
    },
    // 删除
    handleDel(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      delGiftList(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功'
          })
        }
      })
    },
    handleStatus(row) {
      this.currentId = row.id
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('p', null, [h('span', null, '是否要改变当前礼物的状态？ ')]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            editStatus({ id: this.currentId }).then(res => {
              this.getList()
            })
            done()
          } else {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
            done()
          }
        }
      })
        .then(action => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
        .catch(res => res)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}

/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list--text {
  max-height : 100px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list__item-name {
  white-space : normal !important;
}
</style>
